﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Zj.CourseManage.Repository.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using Zj.CourseManage.Domain.Events;
using Zj.CourseManage.Messaging.Simple;
using Zj.CourseManage.EventHandler;
using Zj.CourseManage.EventStore.SQLServer;

namespace Zj.CourseManage.Mvc
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //var conn = @"Server=.;Database=CourseManageDb;Uid=sa;Pwd=Sa1234;Integrated Security=false";
            //services.AddDbContext<CourseDbContext>(option => option.UseSqlServer(conn));
            var cfg= Configuration.GetConnectionString("default");
            services.AddDbContext<CourseDbContext>(option => option.UseSqlServer(cfg));


            services.AddScoped<DbContext,CourseDbContext>();
            services.AddMvc(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
            //services.AddMvc(options => options.Filters.Add(new ValidateAntiForgeryTokenAttribute()));

            services.AddSingleton<IEventBus, SimpleEventBus>();
            services.AddTransient<IEventHandler, StudentCreatedEventHandler>();
            services.AddTransient<IEventStore, SQLServerEventStore>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            var eventBus=app
                .ApplicationServices
                .CreateScope()
                .ServiceProvider
                .GetRequiredService<IEventBus>();
            eventBus.Subscribe();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

        }
    }
}
